package com.zhny.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhny.dao.DeviceAndIndexDao;
import com.zhny.dao.DeviceDao;
import com.zhny.entity.QueryPageBean;
import com.zhny.pojo.Device;
import com.zhny.pojo.DeviceAndIndex;
import com.zhny.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import tk.mybatis.mapper.entity.Example;

@Service
@Component //这个在spring中注册，由spring管理的组件，不用Service是因为为了避免与dubbo的service冲突（而忘了import）
public class DeviceServiceImpl implements DeviceService {
    @Autowired
    private DeviceDao deviceDao;

    @Autowired
    private DeviceAndIndexDao deviceAndIndexDao;

    @Override
    public void add(Device device) {
        deviceDao.insertSelective(device);
        DeviceAndIndex deviceAndIndex = device.getDeviceAndIndex();
        deviceAndIndex.setDid(device.getId());
        deviceAndIndexDao.insertSelective(deviceAndIndex);
    }

    @Override
    public Page<Device> findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        if (!StringUtils.isEmpty(queryPageBean.getQueryString())) {
            Example example = new Example(Device.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.orEqualTo("code", queryPageBean.getQueryString());
            criteria.orEqualTo("name", queryPageBean.getQueryString());
            Page<Device> page = (Page<Device>) deviceDao.selectByExample(example);
            return page;
        }
        Page<Device> page = (Page<Device>) deviceDao.selectAll();
        return page;
    }

    @Override
    public void update(Device device) {
        deviceDao.updateByPrimaryKey(device);
    }

    @Override
    public void delete(Integer deviceId) {
        Example example = new Example(DeviceAndIndex.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("did",deviceId);
        deviceAndIndexDao.deleteByExample(example);
        deviceDao.deleteByPrimaryKey(deviceId);
    }
}
